﻿using Sunny.UI;
using System.Diagnostics;
using Sunny.UI.Win32;
using OfficeOpenXml;
using System.Collections.Generic;
using static WinFormsApp1.Form1;
using System.Drawing;
using OfficeOpenXml.Utils;
using System.Text;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : UIEditForm
    {
        List<Data> datas = new List<Data>();
        public Form1()
        {
            InitializeComponent();
            //SunnyUI封装的加列函数，也可以和原生的一样，从Columns里面添加列
            uiDataGridView1.AddColumn("序号", "idx");
            uiDataGridView1.AddColumn("X(m)", "X");
            uiDataGridView1.AddColumn("Y(m)", "Y");
            uiDataGridView1.AddColumn("Z(m)", "Z");
            uiDataGridView2.AddColumn("点号", "idx");
            uiDataGridView2.AddColumn("经度(°)", "lon");
            uiDataGridView2.AddColumn("纬度（°）", "lat");
            uiDataGridView2.AddColumn("X(m)", "X");
            uiDataGridView2.AddColumn("Y(m)", "Y");
            uiDataGridView2.AddColumn("高程(m)", "Z");
            uiDataGridView2.AddColumn("相对误差", "error");
            uiDataGridView3.AddColumn("序号", "idx");
            uiDataGridView3.AddColumn("原始X(m)", "X");
            uiDataGridView3.AddColumn("原始Y(m)", "Y");
            uiDataGridView3.AddColumn("原始Z(m)", "Z");
            uiDataGridView3.AddColumn("输出X(m)", "X2");
            uiDataGridView3.AddColumn("输出Y(m)", "Y2");
            uiDataGridView3.AddColumn("输出Z(m)", "Z2");
            uiDataGridView3.AddColumn("较差", "jc");
            uiDataGridView3.AddColumn("中误差", "zwc");

            //SunnyUI常用的初始化配置，看个人喜好用或者不用。
            uiDataGridView1.Init();
            uiDataGridView2.Init();
            uiDataGridView3.Init();


        }
        public string folderName;
        public string listAsString;
        private void uiTextBox1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "请选择文件";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                Infilename.Text = openFileDialog.FileName;
                folderName = Path.GetDirectoryName(openFileDialog.FileName);
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "python";
                String pythonScriptPath = "G:\\pythonProject\\surveying_mapping\\data_input.py";
                String argument1 = Infilename.Text;
                String argument2 = null;
                String zux = uiTextBox1.Text;
                String errorfile = folderName + "\\erro.log";
                string pro = uiComboBox4.Text;
                if (CoorSys.Text != "自定义椭球")
                {
                    argument2 = CoorSys.Text;
                    startInfo.Arguments = $"{pythonScriptPath} {argument1} {errorfile} {argument2} {zux} {"0"} {"0"} {pro}";
                }
                else
                {
                    argument2 = inbztext.Text;
                    string argument3 = inbltext.Text;
                    startInfo.Arguments = $"{pythonScriptPath} {argument1} {errorfile} {"自定义椭球"} {zux} {argument2} {argument3} {pro}";
                }

                startInfo.RedirectStandardOutput = true;
                // 启动进程并等待完成  

                Process process = new Process();
                process.StartInfo = startInfo;
                startInfo.CreateNoWindow = true;
                process.Start();
                /*ShowStatusForm(100, "数据检查中......", 0);
                for (int i = 0; i < 100; i++)
                {
                    SystemEx.Delay(50);
                    SetStatusFormDescription("数据检查中(" + i + "%)......");
                    StatusFormStepIt();
                }
                HideStatusForm();*/
                // 读取进程的输出（可选）  
                StreamReader reader = process.StandardOutput;
                string result = reader.ReadToEnd();
                MessageBox.Show(result);
                process.WaitForExit();
                loadexc(Infilename.Text, "in");
                uiDataGridView1.DataSource = datas;
                uiDataGridView1.SelectIndexChange += uiDataGridView1_SelectIndexChange;
            }
            catch (Exception err)
            {
                ShowErrorTip("请正确输入数据");
            }


        }

        private void Form1_Load(object sender, EventArgs e)
        {
            zdyname.Visible = false;
            inblname.Visible = false;
            inbltext.Visible = false;
            inbzname.Visible = false;
            inbztext.Visible = false;
            inbltext.Text = string.Empty;
            inbztext.Text = string.Empty;
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            Infilename.Text = "";
            CoorSys.Text = "";
            uiComboBox4.Text = "高斯克吕格投影";
            uiTextBox1.Text = "117";
            zdyvisile(false);
            uiDataGridView1.DataSource = "";
        }



        private void uiRadioButton5_CheckedChanged(object sender, EventArgs e)
        {

        }

        public class Data
        {
            public string X { get; set; }

            public string Y { get; set; }
            public string Z { get; set; }
            public string idx { get; set; }
            public string lon { get; set; }
            public string lat { get; set; }
            public string error { get; set; }
            public bool Column4 { get; set; }
            public string X2 { get; set; }
            public string Y2 { get; set; }
            public string Z2 { get; set; }
            public string jc { get; set; }
            public string zwc { get; set; }
            public override string ToString()
            {
                return X;
            }
        }


        private void uiDataGridView1_SelectIndexChange(object sender, int index)
        {
            index.WriteConsole("SelectedIndex");
        }
        private void uiDataGridView2_SelectIndexChange(object sender, int index)
        {
            index.WriteConsole("SelectedIndex");
        }
        private void uiDataGridView3_SelectIndexChange(object sender, int index)
        {
            index.WriteConsole("SelectedIndex");
        }
        #region
        /*数据读取*/
        private void loadexc(String filepathh, String mode)
        {
            datas = new List<Data>();
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            FileInfo fileInfo = new FileInfo(filepathh);
            List<String> rowlist = new List<string>();
            List<List<String>> list = new List<List<string>>();
            using (ExcelPackage package = new ExcelPackage(fileInfo))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; // 假设要读取第一个工作表
                int rowCount = worksheet.Dimension.Rows;
                int columnCount = worksheet.Dimension.Columns;
                for (int row = 1; row <= rowCount; row++)
                {
                    for (int column = 1; column <= columnCount; column++)
                    {
                        string cellValue = worksheet.Cells[row, column].Value?.ToString();
                        rowlist.Add(cellValue);
                    }
                    list.Add(rowlist);
                    rowlist = new List<string>();
                }
            }
            if (mode == "out" || mode == "checksys")
            {
                for (int i = 1; i < (list.Count); i++)
                {
                    Data data = new Data();
                    if (mode == "out")
                    {
                        if (i > 0)
                        {
                            data.idx = list[i][0];
                            data.lon = list[i][1];
                            data.lat = list[i][2];
                            data.X = list[i][3];
                            data.Y = list[i][4];
                            data.Z = list[i][5];
                            data.error = list[i][6];
                        }
                    }
                    if (mode == "checksys")
                    {
                        if (i > 0)
                        {
                            data.idx = i.ToString();
                            data.X = list[i][0];
                            data.Y = list[i][1];
                            data.Z = list[i][2];
                            data.X2 = list[i][3];
                            data.Y2 = list[i][4];
                            data.Z2 = list[i][5];
                            data.jc = list[i][6];
                            data.zwc = list[i][7];
                        }
                    }
                    datas.Add(data);
                }
            }

            else
            {
                for (int i = 0; i < (list.Count); i++)
                {
                    Data data = new Data();

                    data.idx = list[i][0];
                    data.X = list[i][1];
                    data.Y = list[i][2];
                    data.Z = list[i][3];
                    datas.Add(data);
                }
            }

            base.Init();
        }
        #endregion

        private void uiComboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (uiComboBox3.Text == "自定义椭球")
            {
                InCoor coor = new InCoor();
                coor.ShowDialog();
                String argument1 = coor.bz;
                string argument4 = coor.zwx;
                coor.Dispose();

            }
        }

        private void uiButton4_Click(object sender, EventArgs e)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "G:\\pythonProject\\surveying_mapping\\venv\\Scripts\\python.exe";
                string pythonScriptPath = "G:\\pythonProject\\surveying_mapping\\data_output.py";
                string argument1 = Infilename.Text;
                string firstcoor = CoorSys.Text;
                string coorresult = uiComboBox3.Text;
                string errorfile = folderName + "\\erro.log";
                string firstzwx = uiTextBox1.Text;
                string zwxresult = uiTextBox5.Text;
                string outfilepath = uiTextBox2.Text;
                string filetype = uiComboBox2.Text;
                string datatype = uiComboBox1.Text;
                string Dvalue = "是";
                string pram = uiComboBox5.Text;
                string inpro = uiComboBox4.Text; ;
                string outpro = uiComboBox6.Text; ;
                if (uiRadioButton2.Checked)
                {
                    Dvalue = "否";
                }
                string coortype = "全选";
                if (firstcoor != "自定义椭球" && coorresult != "自定义椭球")
                {
                    startInfo.Arguments = $"{pythonScriptPath} {argument1} {errorfile} {firstcoor} {firstzwx} {"0"} {"0"} {coorresult} {zwxresult} " +
                        $"{Dvalue} {"0"} {"0"} {outfilepath} {filetype} {coortype} {datatype} {pram} {inpro} {outpro} {listAsString}";
                }
                else if (firstcoor == "自定义椭球" && coorresult != "自定义椭球")
                {
                    zdyvisile(true);
                    string bz = inbztext.Text;
                    string bl = inbltext.Text;
                    startInfo.Arguments = $"{pythonScriptPath} {argument1} {errorfile} {firstcoor} {firstzwx} {bz} {bl} {coorresult} {zwxresult} " +
                        $"{Dvalue} {"0"} {"0"} {outfilepath} {filetype} {coortype} {datatype} {pram} {inpro} {outpro}";
                }
                else if (firstcoor != "自定义椭球" && coorresult == "自定义椭球")
                {
                    InCoor coor = new InCoor();
                    coor.ShowDialog();
                    string bz = coor.bz;
                    string bl = coor.bl;
                    coor.Dispose();
                    startInfo.Arguments = $"{pythonScriptPath} {argument1} {errorfile} {firstcoor} {firstzwx} {"0"} {"0"} {coorresult} {zwxresult} " +
                       $"{Dvalue} {bz} {bl} {outfilepath} {filetype} {coortype} {datatype} {pram} {inpro} {outpro}";
                }
                else
                {
                    zdyvisile(true);
                    InCoor coor = new InCoor();
                    coor.ShowDialog();
                    string bz = coor.bz;
                    string bl = coor.bl;
                    coor.Dispose();
                    startInfo.Arguments = $"{pythonScriptPath} {argument1} {errorfile} {firstcoor} {firstzwx} {Text} {inbltext.Text} {coorresult} {zwxresult} " +
                      $"{Dvalue} {bz} {bl} {outfilepath} {filetype} {coortype} {datatype} {pram} {inpro} {outpro}";
                }
                startInfo.RedirectStandardOutput = true;
                // 启动进程并等待完成  

                Process process = new Process();
                process.StartInfo = startInfo;
                startInfo.CreateNoWindow = true;
                process.Start();

                /*ShowStatusForm(100, "数据检查中......", 0);
                for (int i = 0; i < 100; i++)
                {
                    SystemEx.Delay(50);
                    SetStatusFormDescription("数据检查中(" + i + "%)......");
                    StatusFormStepIt();
                }
                HideStatusForm();*/
                // 读取进程的输出（可选）  
                process.WaitForExit();
                if (uiComboBox2.Text == "Xlsx格式")
                {
                    loadexc(outfilepath + "\\BL_XY坐标.xlsx", "out");
                }
                else { loadexc(outfilepath + "\\BL_XY坐标.csv", "out"); }
                uiDataGridView2.DataSource = datas;
                uiDataGridView2.SelectIndexChange += uiDataGridView2_SelectIndexChange;
            }
            catch (Exception err)
            {

                ShowErrorTip("请正确输入数据");
            }
        }


        private void uiTextBox2_MouseDown(object sender, MouseEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                uiTextBox2.Text = dialog.SelectedPath;
            }
        }

        private void tabPage3_Click(object sender, EventArgs e)
        {

        }
        private void zdyvisile(bool iflook)
        {
            if (iflook)
            {
                zdyname.Visible = true;
                inblname.Visible = true;
                inbltext.Visible = true;
                inbzname.Visible = true;
                inbztext.Visible = true;
            }
            else
            {
                zdyname.Visible = false;
                inblname.Visible = false;
                inbltext.Visible = false;
                inbzname.Visible = false;
                inbztext.Visible = false;
                inbltext.Text = string.Empty;
                inbztext.Text = string.Empty;
            }
        }
        private void CoorSys_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (CoorSys.Text == "自定义椭球")
            {
                zdyvisile(true);

            }
            else
            {
                zdyvisile(false);
            }
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            uiComboBox6.Text = "高斯克吕格投影";
            uiComboBox5.Text = string.Empty;
            uiComboBox3.Text = string.Empty;
            uiTextBox5.Text = "117";
            uiComboBox1.Text = string.Empty;
            uiRadioButton1.Checked = false;
            uiRadioButton2.Checked = false;
            uiComboBox2.Text = string.Empty;
            uiTextBox2.Text = string.Empty;
            uiDataGridView2.DataSource = "";
        }

        private void uiButton7_Click(object sender, EventArgs e)
        {
            loadexc("E:\\work\\QualityInspection\\surveying_mapping-master\\data\\" + "BL_XY坐标.xlsx", "out");
            uiDataGridView2.DataSource = datas;
            uiDataGridView2.SelectIndexChange += uiDataGridView2_SelectIndexChange;
        }

        private void uiComboBox4_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void uiComboBox4_TextChanged(object sender, EventArgs e)
        {
            if (uiComboBox4.Text == "高斯克吕格投影")
            {
                uiLabel14.Text = "中央子午线";
                uiTextBox1.Text = "117";
            }
            if (uiComboBox4.Text == "UTM")
            {
                uiLabel14.Text = "Zone";
                uiTextBox1.Text = "";

            }
        }

        private void uiComboBox6_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (uiComboBox6.Text == "高斯克吕格投影")
            {
                uiLabel15.Text = "中央子午线";
                uiTextBox5.Text = "117";
            }
            if (uiComboBox6.Text == "UTM")
            {
                uiLabel15.Text = "Zone";
                uiTextBox5.Text = "";

            }
        }

        private void uiTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }





        private void uiTextBox6_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "请选择文件";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "*dxf文件(*.dxf)|*.dxf";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                uiTextBox6.Text = openFileDialog.FileName;
            }
        }

        private void uiTextBox4_Click(object sender, EventArgs e)
        {

        }



        private void uiTextBox3_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "请选择文件";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "文本文件(*.txt)|*.txt";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                uiTextBox3.Text = openFileDialog.FileName;
            }
        }

        private void uiButton5_Click(object sender, EventArgs e)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "G:\\pythonProject\\surveying_mapping\\venv\\Scripts\\python.exe";
                String pythonScriptPath = "G:\\pythonProject\\surveying_mapping\\dxf_read.py";
                String argument1 = uiTextBox6.Text;
                startInfo.Arguments = $"{pythonScriptPath} {argument1}";
                startInfo.RedirectStandardOutput = true;
                // 启动进程并等待完成  
                Process process = new Process();
                process.StartInfo = startInfo;
                startInfo.CreateNoWindow = true;
                process.Start();
                /*ShowStatusForm(100, "数据检查中......", 0);
                for (int i = 0; i < 100; i++)
                {
                    SystemEx.Delay(50);
                    SetStatusFormDescription("数据检查中(" + i + "%)......");
                    StatusFormStepIt();
                }
                HideStatusForm();*/
                // 读取进程的输出（可选）  
                StreamReader reader = process.StandardOutput;
                string result = reader.ReadToEnd();
                string[] finalresult = result.Split("\r\n");
                for (int i = 0; i < finalresult.Length; i++)
                {
                    uiListBox1.Items.Add(finalresult[i]);
                }
                process.WaitForExit();
            }
            catch (Exception err)
            {
                ShowErrorTip("请正确输入数据");
            }
        }

        private void uiButton6_Click(object sender, EventArgs e)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "G:\\pythonProject\\surveying_mapping\\venv\\Scripts\\python.exe";
                String pythonScriptPath = "G:\\pythonProject\\surveying_mapping\\dxf_match.py";
                String argument1 = uiTextBox3.Text;
                String argument2 = uiTextBox6.Text;
                String argument3 = "是";
                if (uiRadioButton3.Checked)
                {
                    argument3 = "否";
                }
                String argument4 = uiListBox1.SelectedItems[0].ToString();
                String argument5 = uiTextBox4.Text;
                startInfo.Arguments = $"{pythonScriptPath} {argument1} {argument2} {argument3} {argument4} {argument5} ";
                startInfo.RedirectStandardOutput = true;
                // 启动进程并等待完成  

                Process process = new Process();
                process.StartInfo = startInfo;
                startInfo.CreateNoWindow = true;
                process.Start();
                /*ShowStatusForm(100, "数据检查中......", 0);
                for (int i = 0; i < 100; i++)
                {
                    SystemEx.Delay(50);
                    SetStatusFormDescription("数据检查中(" + i + "%)......");
                    StatusFormStepIt();
                }
                HideStatusForm();*/
                // 读取进程的输出（可选）  
                process.WaitForExit();
                loadexc(uiTextBox4.Text + "/测绘成品质量检查精度.xlsx", "checksys");
                uiDataGridView3.DataSource = datas;
                uiDataGridView3.SelectIndexChange += uiDataGridView3_SelectIndexChange;
            }
            catch (Exception err)
            {
                ShowErrorTip("请正确输入数据");
            }
        }

        private void uiButton7_Click_1(object sender, EventArgs e)
        {
            uiTextBox3.Text = "";
            uiTextBox4.Text = "";
            uiTextBox6.Text = "";
            uiRadioButton3.Checked = false;
            uiRadioButton4.Checked = false;
            uiDataGridView3.DataSource = "";
            uiListBox1.Items.Clear();
        }

        private void uiTextBox4_Click_1(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                uiTextBox4.Text = dialog.SelectedPath;
            }
        }

        private void tabPage4_Click(object sender, EventArgs e)
        {

        }

        private void uiButton8_Click(object sender, EventArgs e)
        {
            uiTextBox3.Text = "";
            uiTextBox4.Text = "";
            uiTextBox6.Text = "";
            uiRadioButton3.Checked = false;
            uiRadioButton4.Checked = false;
            uiDataGridView3.DataSource = "";
            uiListBox1.Items.Clear();
        }



        private void uiComboBox5_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (uiComboBox5.Text == "四参数")
            {
                FourParamsTransform transform = new FourParamsTransform();
                transform.ShowDialog();

                List<string> stringsList = transform.stringsList;
                listAsString = string.Join(",", stringsList);
                transform.Dispose();
            }
            if (uiComboBox5.Text == "七参数")
            {
                Transform transform = new Transform();
                transform.ShowDialog();
                List<string> stringsList = transform.stringsList;
                listAsString = string.Join(",", stringsList);
                transform.Dispose();
            }
            else { }
        }
    }
}

